#!/usr/bin/env python
# -- coding: utf-8 --
# @Time : 2023/1/17 16:37
# @Coder: Pithon
# @IDE : PyCharm
# @WEB : http://pithon.top
# ==============================
import calendar
import json
from datetime import datetime
import pandas as pd
import requests
from fake_useragent import UserAgent


def get_top(request_data):
    base_url = 'http://index.baidu.com/insight/brand/queryTradeRank'
    cookie = 'BDUSS=VpuYkltMUxDU3ZPRTh2enFTRW1keGZFU0xrSHRFTjJVWDViN21lZlFEM2pBZDVqRVFBQUFBJCQAAAAAAAAAAAEAAABcOMpVeXBzMTg0eGgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAON0tmPjdLZjM'
    ua = str(UserAgent().random)
    headers = {
        'Accept': 'application/json, text/plain, */*',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Content-Type': 'application/json;charset=UTF-8',
        'Proxy-Connection': 'keep-alive',
        'Cookie': cookie,
        'Host': 'index.baidu.com',
        'Referer': 'http://index.baidu.com/v2/rank/index.html?',
        'User-Agent': ua,
        'X-Requested-With': 'XMLHttpRequest'
    }

    res = requests.post(base_url, data=json.dumps(request_data), headers=headers)
    return res.json()['data']['data']


def construct_data(date, industry, channel='index', num=10):
    """
    :param date:每次只能请求一天的数据，开始时间和结束时间为同一天
    :param industry: ['汽车', '手机', '电脑办公', '家用电器', '化妆品', '旅游景点', '家具家居', '家装平台', '房产行业   ', '婴幼儿奶粉']
    :param channel: index指数、search搜索指数、feed资讯指数、click互动指数
    :param num:获取前多少个数据
    :return:post请求的字典数据
    """
    # 字典表
    industry_params = {
        'car': [8, 1017],
        'phone': [12, 1008],
        'computer': [12, 1026],
        'appliance': [12, 1010],
        'makeup': [2, 1001],
        'tourist': [16, 1030],
        'furniture': [3, 1016],
        'decorationPlatform': [3, 1022],
        'estate': [3, 1006],
        'milkPowder': [17, 1000],
    }
    data = {
        "topNum": num,
        "startDate": datetime.strftime(date, '%Y-%m-%d'),
        "endDate": datetime.strftime(date, '%Y-%m-%d'),
        "channel": channel,
        "trade1": industry_params[industry][0],
        "trade2": industry_params[industry][1],
        "rankType": "daily",
        "type": "brand",
    }
    return data


def get_monthly_data(industry, year, month):
    result_df = pd.DataFrame(columns=['entityId', 'entityName', 'value', 'rank', 'trend', 'occupy', 'date'])
    start = datetime(year, month, 1)
    end = datetime(year, month, calendar.monthrange(year, month)[1])
    for date in pd.date_range(start, end):
        request_data = construct_data(date, industry)
        res_data = get_top(request_data)
        df = pd.DataFrame(res_data)
        df['date'] = datetime.strftime(date, '%Y-%m-%d')
        result_df = pd.concat([result_df, df])
    result_df.to_csv(r'./rank_download/{}_{}{}.csv'.format(industry, year, month), index=False, encoding='utf8')
